using BuildingBlocks.Core.Entities;
using System.Text.RegularExpressions;

namespace Identity.Domain.ValueObjects;
public class EmailAddress : ValueObject
{
    public string Value { get; } = default!; // 邮箱地址

    private EmailAddress() { } // for EF

    private EmailAddress(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
            throw new ArgumentException("Email address cannot be empty.", nameof(value));

        if (!IsValidEmail(value))
            throw new ArgumentException("Invalid email address format.", nameof(value));

        Value = value;
    }

    public static EmailAddress From(string value) => new EmailAddress(value);



    public override string ToString() => Value;

    private static bool IsValidEmail(string email)
    {
        return Regex.IsMatch(email,
            @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase);
    }

    protected override IEnumerable<object> GetEqualityComponents()
    {
        yield return Value.ToLowerInvariant(); // 忽略大小写比较
    }
}